using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Bullet : MonoBehaviour
{
    public enum BulletType{
        C=0,
        M,
        S,
        L,
        R,
        B,
    }

    [Tooltip("子弹伤害点")]
    public int damagePoint=1;

    // 子弹是否发射
    protected bool run;
    // 子弹飞行速度在模拟器中测量30帧移动了90个像素
    protected float speed=(90f/16f)/(30f/60f);
    
    // BulletMeta定义了子弹的飞行方向
    protected BulletMeta meta=new(); 

    // 子弹刚体
    protected Rigidbody2D rig;

    protected virtual void Awake()
    {
        rig=GetComponent<Rigidbody2D>();

        // 默认情况下子弹飞行方向设置为向右发射
        meta.sourcePoint=transform.position;
        meta.targetPoint=meta.sourcePoint+Vector2.right+Vector2.up;
    }

    protected virtual void FixedUpdate()
    {
        if(run){
            // 让子弹飞行
            rig.velocity=speed*meta.Direction;
        }
    }

    /// <summary>
    /// 子弹在创建后不会立刻飞行，需要调用Launch方法来让子弹飞行
    /// </summary>
    /// <param name="meta">子弹的飞行方向</param>
    public void Launch(BulletMeta meta){
        if(meta!=null){
            this.meta=meta;
        }
        this.run=true;
    }

    void OnTriggerEnter2D(Collider2D collider){
        if(collider.TryGetComponent(out Damageable damageable)){
            damageable.Damage(gameObject,damagePoint);
            Boom();
        }
    }

    // 子弹命中后爆炸效果
    void Boom(){
        Instantiate(Constant.Prefabs.BulletBoom1.Load(),transform.position,Quaternion.identity);
        Destroy(gameObject);
    }
}

/// <summary>
/// 描述子弹飞行方向
/// </summary>
public class BulletMeta{
    // 子弹发射的初始位置
    public Vector2 sourcePoint;
    
    // 子弹飞行的方向位置
    public Vector2 targetPoint;

    // 通过计算返回方向向量
    public Vector2 Direction{
        get{
            return (targetPoint-sourcePoint).normalized;
        }
    }

    public override string ToString()
    {
        return "sourcePoint:"+sourcePoint+"  ,targetPoint:"+targetPoint+"  ,Direction:"+Direction;
    }
}


